/**
 * 通知路由模块
 * @author HalRui
 * @version 1.0.0
 * @description 定义通知相关的API接口，包括通知创建、查询、标记已读、删除、统计等功能
 * @date 2025年9月27日
 */

const express = require('express');
const router = express.Router();
const notificationsApi = require('../../api/notifications-api');

/**
 * 创建通知
 * POST /notifications/create
 */
router.post('/create', async (req, res) => {
    try {
        const {
            userId,
            type,
            title,
            content,
            data,
            fromUserId,
            targetType,
            targetId,
            priority,
            expiresAt
        } = req.body;
        
        // 参数验证
        if (!userId || !type || !title || !content) {
            return res.status(400).json({
                success: false,
                message: '缺少必要参数：userId, type, title, content'
            });
        }
        
        // 验证通知类型
        const validTypes = [
            'like', 'comment', 'reply', 'follow', 'favorite', 
            'message', 'system', 'video_upload', 'video_approved', 
            'video_rejected', 'mention'
        ];
        if (!validTypes.includes(type)) {
            return res.status(400).json({
                success: false,
                message: '无效的通知类型'
            });
        }
        
        // 验证优先级
        if (priority && !['low', 'normal', 'high', 'urgent'].includes(priority)) {
            return res.status(400).json({
                success: false,
                message: '无效的优先级'
            });
        }
        
        const notificationData = {
            userId: parseInt(userId),
            type,
            title,
            content,
            data: data || {},
            fromUserId: fromUserId ? parseInt(fromUserId) : null,
            targetType: targetType || null,
            targetId: targetId ? parseInt(targetId) : null,
            priority: priority || 'normal',
            expiresAt: expiresAt ? new Date(expiresAt) : null
        };
        
        const result = await notificationsApi.createNotification(notificationData);
        
        if (result.success) {
            res.status(201).json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('创建通知接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 批量创建通知
 * POST /notifications/batch-create
 */
router.post('/batch-create', async (req, res) => {
    try {
        const { notifications } = req.body;
        
        // 参数验证
        if (!notifications || !Array.isArray(notifications) || notifications.length === 0) {
            return res.status(400).json({
                success: false,
                message: '缺少有效的通知数据数组'
            });
        }
        
        if (notifications.length > 1000) {
            return res.status(400).json({
                success: false,
                message: '批量创建通知数量不能超过1000条'
            });
        }
        
        // 验证每个通知的必要参数
        for (const notification of notifications) {
            if (!notification.userId || !notification.type || !notification.title || !notification.content) {
                return res.status(400).json({
                    success: false,
                    message: '每个通知都必须包含：userId, type, title, content'
                });
            }
        }
        
        const result = await notificationsApi.createBatchNotifications(notifications);
        
        if (result.success) {
            res.status(201).json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('批量创建通知接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取用户通知列表
 * GET /notifications/list/:userId
 */
router.get('/list/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        const { type, isRead, priority, page = 1, limit = 20 } = req.query;
        
        // 参数验证
        if (!userId || isNaN(parseInt(userId))) {
            return res.status(400).json({
                success: false,
                message: '无效的用户ID'
            });
        }
        
        const pageNum = parseInt(page);
        const limitNum = parseInt(limit);
        
        if (pageNum < 1 || limitNum < 1 || limitNum > 100) {
            return res.status(400).json({
                success: false,
                message: '无效的分页参数'
            });
        }
        
        const options = {
            userId: parseInt(userId),
            page: pageNum,
            limit: limitNum
        };
        
        if (type) options.type = type;
        if (isRead !== undefined) options.isRead = isRead === 'true';
        if (priority) options.priority = priority;
        
        const result = await notificationsApi.getUserNotifications(options);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('获取用户通知列表接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取通知详情
 * GET /notifications/detail/:notificationId/:userId
 */
router.get('/detail/:notificationId/:userId', async (req, res) => {
    try {
        const { notificationId, userId } = req.params;
        
        // 参数验证
        if (!notificationId || isNaN(parseInt(notificationId))) {
            return res.status(400).json({
                success: false,
                message: '无效的通知ID'
            });
        }
        
        if (!userId || isNaN(parseInt(userId))) {
            return res.status(400).json({
                success: false,
                message: '无效的用户ID'
            });
        }
        
        const result = await notificationsApi.getNotificationDetail(
            parseInt(notificationId),
            parseInt(userId)
        );
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(404).json(result);
        }
    } catch (error) {
        console.error('获取通知详情接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 标记通知为已读
 * PUT /notifications/mark-read
 */
router.put('/mark-read', async (req, res) => {
    try {
        const { userId, notificationIds, type } = req.body;
        
        // 参数验证
        if (!userId || isNaN(parseInt(userId))) {
            return res.status(400).json({
                success: false,
                message: '无效的用户ID'
            });
        }
        
        if (notificationIds && !Array.isArray(notificationIds)) {
            return res.status(400).json({
                success: false,
                message: '通知ID列表必须是数组'
            });
        }
        
        const options = {
            userId: parseInt(userId)
        };
        
        if (notificationIds && notificationIds.length > 0) {
            options.notificationIds = notificationIds.map(id => parseInt(id));
        }
        
        if (type) options.type = type;
        
        const result = await notificationsApi.markNotificationsAsRead(options);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('标记通知为已读接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 删除通知
 * DELETE /notifications/delete
 */
router.delete('/delete', async (req, res) => {
    try {
        const { userId, notificationIds, type, olderThan } = req.body;
        
        // 参数验证
        if (!userId || isNaN(parseInt(userId))) {
            return res.status(400).json({
                success: false,
                message: '无效的用户ID'
            });
        }
        
        if (notificationIds && !Array.isArray(notificationIds)) {
            return res.status(400).json({
                success: false,
                message: '通知ID列表必须是数组'
            });
        }
        
        const options = {
            userId: parseInt(userId)
        };
        
        if (notificationIds && notificationIds.length > 0) {
            options.notificationIds = notificationIds.map(id => parseInt(id));
        }
        
        if (type) options.type = type;
        if (olderThan) options.olderThan = new Date(olderThan);
        
        const result = await notificationsApi.deleteNotifications(options);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('删除通知接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取未读通知数量
 * GET /notifications/unread-count/:userId
 */
router.get('/unread-count/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        const { type } = req.query;
        
        // 参数验证
        if (!userId || isNaN(parseInt(userId))) {
            return res.status(400).json({
                success: false,
                message: '无效的用户ID'
            });
        }
        
        const result = await notificationsApi.getUnreadCount(parseInt(userId), type);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('获取未读通知数量接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取通知统计
 * GET /notifications/stats/:userId
 */
router.get('/stats/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        
        // 参数验证
        if (!userId || isNaN(parseInt(userId))) {
            return res.status(400).json({
                success: false,
                message: '无效的用户ID'
            });
        }
        
        const result = await notificationsApi.getNotificationStats(parseInt(userId));
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('获取通知统计接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取系统通知
 * GET /notifications/system
 */
router.get('/system', async (req, res) => {
    try {
        const { page = 1, limit = 20, priority } = req.query;
        
        const pageNum = parseInt(page);
        const limitNum = parseInt(limit);
        
        if (pageNum < 1 || limitNum < 1 || limitNum > 100) {
            return res.status(400).json({
                success: false,
                message: '无效的分页参数'
            });
        }
        
        const options = {
            page: pageNum,
            limit: limitNum
        };
        
        if (priority) options.priority = priority;
        
        const result = await notificationsApi.getSystemNotifications(options);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('获取系统通知接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 发送系统广播通知
 * POST /notifications/broadcast
 */
router.post('/broadcast', async (req, res) => {
    try {
        const { title, content, data, priority, expiresAt, userIds } = req.body;
        
        // 参数验证
        if (!title || !content) {
            return res.status(400).json({
                success: false,
                message: '缺少必要参数：title, content'
            });
        }
        
        if (!userIds || !Array.isArray(userIds) || userIds.length === 0) {
            return res.status(400).json({
                success: false,
                message: '缺少有效的用户ID列表'
            });
        }
        
        if (userIds.length > 10000) {
            return res.status(400).json({
                success: false,
                message: '广播用户数量不能超过10000个'
            });
        }
        
        const notificationData = {
            title,
            content,
            data: data || {},
            priority: priority || 'normal',
            expiresAt: expiresAt ? new Date(expiresAt) : null
        };
        
        const result = await notificationsApi.broadcastSystemNotification(
            notificationData,
            userIds.map(id => parseInt(id))
        );
        
        if (result.success) {
            res.status(201).json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('发送系统广播通知接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 创建点赞通知
 * POST /notifications/like
 */
router.post('/like', async (req, res) => {
    try {
        const { fromUserId, toUserId, videoId } = req.body;
        
        // 参数验证
        if (!fromUserId || !toUserId || !videoId) {
            return res.status(400).json({
                success: false,
                message: '缺少必要参数：fromUserId, toUserId, videoId'
            });
        }
        
        const result = await notificationsApi.createLikeNotification(
            parseInt(fromUserId),
            parseInt(toUserId),
            parseInt(videoId)
        );
        
        if (result.success) {
            res.status(201).json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('创建点赞通知接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 创建评论通知
 * POST /notifications/comment
 */
router.post('/comment', async (req, res) => {
    try {
        const { fromUserId, toUserId, videoId, commentId, content } = req.body;
        
        // 参数验证
        if (!fromUserId || !toUserId || !videoId || !commentId || !content) {
            return res.status(400).json({
                success: false,
                message: '缺少必要参数：fromUserId, toUserId, videoId, commentId, content'
            });
        }
        
        const result = await notificationsApi.createCommentNotification(
            parseInt(fromUserId),
            parseInt(toUserId),
            parseInt(videoId),
            parseInt(commentId),
            content
        );
        
        if (result.success) {
            res.status(201).json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('创建评论通知接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 创建关注通知
 * POST /notifications/follow
 */
router.post('/follow', async (req, res) => {
    try {
        const { fromUserId, toUserId } = req.body;
        
        // 参数验证
        if (!fromUserId || !toUserId) {
            return res.status(400).json({
                success: false,
                message: '缺少必要参数：fromUserId, toUserId'
            });
        }
        
        const result = await notificationsApi.createFollowNotification(
            parseInt(fromUserId),
            parseInt(toUserId)
        );
        
        if (result.success) {
            res.status(201).json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('创建关注通知接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

module.exports = router;